﻿namespace PugLib.UI
{
	using System;
	using System.Diagnostics;
	using System.Diagnostics.CodeAnalysis;

	public sealed class GdiCounter : IDisposable
	{
		private const int GrGdiobjects = 0;

		private readonly int _intialHandleCount;

		public GdiCounter()
		{
			_intialHandleCount = GetGdiObjects();
		}

		#region IDisposable Members

		public void Dispose()
		{
			int currentHandleCount = GetGdiObjects();
			if (_intialHandleCount == currentHandleCount)
			{
				return;
			}
			int change = currentHandleCount - _intialHandleCount;
			if (change > 0)
			{
				Debug.Fail("Handle count changed by: " + change + new StackTrace());
			}
			GC.SuppressFinalize(this);
		}

		#endregion

		[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
		private static int GetGdiObjects()
		{
			IntPtr processHandle = Process.GetCurrentProcess().Handle;
			return processHandle != IntPtr.Zero ? NativeMethods.GetGuiResources(processHandle, GrGdiobjects) : 0;
		}
	}
}